package com.jiecao.news.jiecaonews.backgroung;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jiecao.news.jiecaonews.adapters.NewsAdapter;
import com.jiecao.news.jiecaonews.dto.pb.PBAboutArticle.PBArticles;
import com.jiecao.news.jiecaonews.pojo.NewsListItem;
import com.jiecao.news.jiecaonews.util.PbUtils;
import com.jiecao.news.jiecaonews.util.constants.Constants;

public class GetMoreDataTask extends AsyncTask<Void, Void, String[]> {
	private static final String TAG = "GetMoreDataTask";
	private ArrayList<NewsListItem> mTempItems;
	private ArrayList<NewsListItem> mItems;//新闻条目数据list
	private NewsAdapter mNewsAdapter;//新闻条目list adapter
	private TextView mloadMoreText; // 加载更多view中的按钮
	private String mTime;
	private ProgressBar mloadMoreProgressBar;
	public GetMoreDataTask(ArrayList<NewsListItem> items,NewsAdapter newsAdapter,TextView loadMoreText,ProgressBar loadMoreProgressBar, String time){
		mItems = items;
		mNewsAdapter = newsAdapter;
		mloadMoreText = loadMoreText;
		mTempItems =new ArrayList<NewsListItem>();
		mTime = time;
		mloadMoreProgressBar = loadMoreProgressBar;
		
	}

	@Override
	protected String[] doInBackground(Void... params) {
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm:ss");  
		PBArticles pBArticles = PbUtils.getPBArticles(
				mTime, Constants.NEWS_LIST_NOT_AFTER, Constants.LIST_PAGE_SIZE, null, 0);
		if (pBArticles == null) {
			return null;
		}
		for (int i = 0; i < pBArticles.getArticlesCount(); i++) {
			NewsListItem listItem = new NewsListItem();
			String   date   =  formatter.format(new Date());
			listItem.setAppCreateTime(date);
			listItem.setIcon(pBArticles.getArticles(i).getIcon());
			listItem.setId(pBArticles.getArticles(i).getId());
			listItem.setIntro(pBArticles.getArticles(i).getIntro());
			listItem.setIsReaded(0);
			listItem.setPublishTime(pBArticles.getArticles(i).getPublishTime());
			listItem.setTitle(pBArticles.getArticles(i).getTitle());
			listItem.setShareNum(pBArticles.getArticles(i).getShareNum());
			mTempItems.add(listItem);
		}
		return null;
	}

	/**
	 * 主线程
	 */
	@Override
	protected void onPostExecute(String[] result) {
		mItems.addAll(mTempItems);
		mNewsAdapter.notifyDataSetChanged(); // 数据集变化后,通知adapter
		mloadMoreText.setText("加载更多"); // 恢复按钮文字
		if(mTempItems==null||mTempItems.size()<=0){
			mloadMoreText.setVisibility(View.GONE);
			mloadMoreProgressBar.setVisibility(View.GONE);
		}else{
			mloadMoreProgressBar.setVisibility(View.VISIBLE);
			mloadMoreProgressBar.setVisibility(View.VISIBLE);
		}
		
		super.onPostExecute(result);
	}

}
